<template>
  <el-drawer direction="rtl"  :title="dialogTitle" v-model="dialogVisible" size="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="所属社区" prop="commId">
            <el-tree-select
              v-model="formData.commId"
              :data="communityTree"
              :props="defaultProps"
              check-strictly
              default-expand-all
              placeholder="请选择所属社区"
              value-key="id"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="中间件地址" prop="lfApiUrl">
            <el-input v-model.trim="formData.lfApiUrl" placeholder="请输入中间件地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="账号绑定开关" prop="pullAccountBeforeBindFlag">
            <el-select
                    v-model="formData.pullAccountBeforeBindFlag"
                    placeholder="账号绑定开关"
                    class="!w-240px"
                  >
                    <el-option
                      v-for="dict in bindFlags"
                      :key="(dict.value)"
                      :label="dict.label"
                      :value="(dict.value)"
                    />
                  </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支持会员等级" prop="levelIds">
            <el-select v-model="formData.levelIds" placeholder="是否支持会员等级" multiple clearable class="!w-240px">
              <el-option v-for="level in levelList" :key="level.id" :label="level.name" :value="level.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="支持用户绑定" prop="supportSelfBindFlag">
        <el-select v-model="formData.supportSelfBindFlag" placeholder="是否支持用户绑定" clearable class="!w-240px">
            <el-option
              v-for="dict in supportSelfBindFlags"
              :key="(dict.value)"
              :label="dict.label"
              :value="(dict.value)"
            />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="12">
            <el-form-item label="分账模式" prop="houseDivideFlag">
              <el-select
                    v-model="formData.houseDivideFlag"
                    placeholder="分账模式"
                    class="!w-240px"
                    @change="triggerDivideFlag"
                  >
                    <el-option
                      v-for="dict in sysDivideModeFlags"
                      :key="(dict.value)"
                      :label="dict.label"
                      :value="(dict.value)"
                    />
                  </el-select>
            </el-form-item>
        </el-col>
        <el-col :span="12">
            <el-form-item label="分账规则" prop="divideMode">
              <el-select
                    v-model="formData.divideMode"
                    placeholder="分账规则"
                    class="!w-240px"
                    @change="triggerDivide"
                  >
                    <el-option
                      v-for="dict in getIntDictOptions(DICT_TYPE.NET_DIVIDE_MODE)"
                      :key="parseInt(dict.value)"
                      :label="dict.label"
                      :value="parseInt(dict.value)"
                    />
                  </el-select>
            </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="设置说明" v-if="formData.divideMode != undefined">
        <div v-if="formData.divideMode == 0" style="color: green;">注意：若设置了分账账户1，则扣除手续费后的金额会自动进入兜底账户</div>
        <div v-if="formData.divideMode == 1" style="color: red;">设置房东/抽成人员分成比例即可，剩余比例会自动进入兜底账户</div>
        <div v-if="formData.divideMode == 2" style="color: blue;">设置房东/抽成人员分成金额即可，剩余金额会自动进入兜底账户</div>
      </el-form-item>

      <el-row v-if="showMatCode1Flag">
        <el-col :span="12">
          <el-form-item label="分账账户1" prop="divideMatId1">
            <el-input v-model="formData.divideMatUserName1_" :readonly="true">
              <template #append>
                <el-button icon="el-icon-search" @click="openMat('divideMatId1')">选择</el-button>
                <el-button type="success" @click="clearMat('divideMatId1')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="matValueRemarkLabel" prop="divideMatValue1">
            <el-input v-model="formData.divideMatValue1" placeholder="请输入值1">
              <template #append>
                <el-button >{{  matValueAppendRemarkLabel }}</el-button>
                <el-button type="success" @click="clearMat('divideMatValue1')">清空</el-button></template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="showMatCode2Flag">
        <el-col :span="12">
          <el-form-item label="分账账户2" prop="matCodeId2">
            <el-input v-model="formData.divideMatUserName2_" :readonly="true">
              <template #append>
                <el-button icon="el-icon-search" @click="openMat('divideMatId2')">选择</el-button>
                <el-button type="success" @click="clearMat('divideMatId2')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="matValueRemarkLabel" prop="divideMatValue2">
            <el-input v-model="formData.divideMatValue2" placeholder="请输入值2">
              <template #append>
                <el-button >{{  matValueAppendRemarkLabel }}</el-button>
                <el-button type="success" @click="clearMat('divideMatValue2')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-alert title="务必配置兜底账户" type="error" :closable="false"/>
      <el-row>
        <el-col :span="12">
          <el-form-item style="color:red;" label="兜底账户" prop="underTakeMatCode">
            <el-input v-model="formData.underTakeMatName_" placeholder="请输入兜底账户">
              <template #append>
                <el-button icon="el-icon-search" @click="openMat('underTakeMatCode')">选择</el-button>
                <el-button type="success" @click="clearMat('underTakeMatCode')">清空</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="说明" prop="mateValue2">
            <span style="color:red;">扣除手续费+分账账户1+分账账户2 后的余额进入该兜底账户</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>  

  <OwnMeterConfigSelect
    ref="ownMeterConfigSelectRef"
    @confirm-own-meter-config="confirmOwnMeterConfig"
  />
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import * as NetSysConfigApi from '@/api/zwsj/netSysConfig'
import OwnMeterConfigSelect from '@/views/zwsj/common/OwnMeterConfigSelect.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as CommunityApi from '@/api/zwsj/community'
import { getSimpleLevelList } from '@/api/member/level'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const showMatCode1Flag = ref(false)
const showMatCode2Flag = ref(false)
const matValueRemarkLabel = ref('')
const matValueAppendRemarkLabel = ref('')
const sysDivideModeFlags = ref([
  {
    value: true,
    label: '按楼栋分账'
  },
  {
    value: false,
    label: '不按楼栋分账'
  }
]) 
const bindFlags = ref([
  {
    value: true,
    label: '绑定前拉取账号'
  },
  {
    value: false,
    label: '不绑定且不拉取'
  }
])

const supportSelfBindFlags = ref([
  {
    value: true,
    label: '支持自行绑定/解绑'
  },
  {
    value: false,
    label: '不支持'
  }
])

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  commId: undefined,
  lfApiUrl: undefined,
  houseDivideFlag: undefined,
  pullAccountBeforeBindFlag: undefined,
  divideMode: undefined,
  divideMatUserName1_: undefined,
  divideMatId1: undefined,
  divideMatCode1_: undefined,
  divideMatValue1: undefined,
  divideMatUserName2_: undefined,
  divideMatId2: undefined,
  divideMatCode2_: undefined,
  divideMatValue2: undefined,
  underTakeMatCode: undefined,
  underTakeMatName_: undefined,
  levelIds:  [],
  levelNames: undefined,
  supportSelfBindFlag: undefined,
})
const formRules = reactive({
  houseDivideFlag: [{ required: true, message: '分账模式不能为空', trigger: 'blur' }],
  underTakeMatCode: [{ required: true, message: '兜底账户编码不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const communityTree = ref() // 树形结构
const levelList = ref([]) // 会员等级列表

/** 打开弹窗 */
const open = async (type: string, id?: number, commId?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  //设置区域默认值
  formData.value.commId = commId

  //获取会员等级列表
  levelList.value = await getSimpleLevelList();

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await NetSysConfigApi.getNetSysConfig(id)
      triggerDivide()
    } finally {
      formLoading.value = false
    }
  }
  // 获得社区树
  await getTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  //根据会员等级计算出会员等级名称
  if(formData.value && formData.value.levelIds.length > 0){
    let levelNames = []
    levelList.value.forEach(le => {
      if(formData.value.levelIds.includes(le.id)){
        levelNames.push(le.name)
      }
    })
    formData.value.levelNames = levelNames.join(",");
  }else{
    formData.value.levelNames = "";
  }
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as NetSysConfigApi.NetSysConfigVO
    if (formType.value === 'create') {
      await NetSysConfigApi.createNetSysConfig(data)
      message.success(t('common.createSuccess'))
    } else {
      await NetSysConfigApi.updateNetSysConfig(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    commId: undefined,
    lfApiUrl: undefined,
    houseDivideFlag: undefined,
    pullAccountBeforeBindFlag: undefined,
    divideMode: undefined,
    divideMatUserName1_: undefined,
    divideMatId1: undefined,
    divideMatCode1_: undefined,
    divideMatValue1: undefined,
    divideMatUserName2_: undefined,
    divideMatId2: undefined,
    divideMatCode2_: undefined,
    divideMatValue2: undefined,
    underTakeMatCode: undefined,
    underTakeMatName_: undefined,
    levelIds:  [],
    levelNames: undefined,
    supportSelfBindFlag: undefined,
  }
  formRef.value?.resetFields()
}

/** 获得区域树 */
const getTree = async () => {
  communityTree.value = []
  const data = await CommunityApi.listSimpleCommunitys()
  let community: Tree = { id: 0, name: '顶级区域', children: [] }
  community.children = handleTree(data)
  communityTree.value.push(community)
}


// 选择分账功能
const ownMeterConfigSelectRef = ref()
const openMat = async (flag) => {
  ownMeterConfigSelectRef.value.open(flag)
}

const confirmOwnMeterConfig = async ({matCode,flag}) => {
  if(flag !+ undefined && flag != null){
    if(flag == "divideMatId1"){
      formData.value.divideMatUserName1_ = matCode.configRemark
      formData.value.divideMatId1 = matCode.id
      formData.value.divideMatCode1_ = matCode.matCode
    }else if(flag == "divideMatId2"){
      formData.value.divideMatUserName2_ = matCode.configRemark
      formData.value.divideMatId2 = matCode.id
      formData.value.divideMatCode2_ = matCode.matCode
    }else if(flag == "underTakeMatCode"){
      formData.value.underTakeMatName_ = matCode.configRemark
      formData.value.underTakeMatCode = matCode.matCode
    }
  }
}
const clearMat = async (flag) => {
  if(flag !+ undefined && flag != null){
    if(flag == "divideMatId1"){
      formData.value.divideMatUserName1_ = undefined
      formData.value.divideMatId1 = undefined
      formData.value.divideMatCode1_ = undefined
    }else if(flag == "divideMatId2"){
      formData.value.divideMatUserName2_ = undefined
      formData.value.divideMatId2 = undefined
      formData.value.divideMatCode2_ = undefined
    }else if(flag == "underTakeMatCode"){
      formData.value.underTakeMatName_ = undefined
      formData.value.underTakeMatCode = undefined
    }else if(flag == "divideMatValue1"){
      formData.value.divideMatValue1 = undefined
    }else if(flag == "divideMatValue2"){
      formData.value.divideMatValue2 = undefined
    }
  }
}

const triggerDivide = async() => {
  let divideMode = (formData.value.divideMode)
  if(divideMode == 0){
    //清空账户1、2的内容，并显示兜底账户
    // formData.value.divideMatUserName1_ = undefined
    // formData.value.divideMatId1 = undefined
    // formData.value.divideMatCode1_ = undefined
    formData.value.divideMatUserName2_ = undefined
    formData.value.divideMatId2 = undefined
    formData.value.divideMatCode2_ = undefined

    showMatCode1Flag.value = true
    matValueRemarkLabel.value = '比例'
    matValueAppendRemarkLabel.value = '%'

    showMatCode1Flag.value = true
    showMatCode2Flag.value = false
  }else if(divideMode == 1){
    showMatCode1Flag.value = true
    showMatCode2Flag.value = true
    matValueRemarkLabel.value = '比例'
    matValueAppendRemarkLabel.value = '%'
  }else if(divideMode == 2){
    showMatCode1Flag.value = true
    showMatCode2Flag.value = true
    matValueRemarkLabel.value = '金额'
    matValueAppendRemarkLabel.value = '元'
  }
}

const triggerDivideFlag = async() => {
  let houseDivideFlag = (formData.value.houseDivideFlag)
  if(true == houseDivideFlag){
    //按楼栋配置，清空除了兜底账户之外的分账规则信息
    showMatCode1Flag.value = true
    showMatCode2Flag.value = true
    
    formData.value.divideMode = undefined

    formData.value.divideMatUserName2_ = undefined
    formData.value.divideMatId2 = undefined
    formData.value.divideMatCode2_ = undefined

    formData.value.divideMatUserName1_ = undefined
    formData.value.divideMatId1 = undefined
    formData.value.divideMatCode1_ = undefined

    showMatCode1Flag.value = true
    matValueRemarkLabel.value = '比例'
    matValueAppendRemarkLabel.value = '%'

    showMatCode1Flag.value = true
    showMatCode2Flag.value = false
  }
}

</script>
